package com.zzy;

import com.alibaba.dashscope.audio.ttsv2.SpeechSynthesisParam;
import com.alibaba.dashscope.audio.ttsv2.SpeechSynthesizer;
import com.alibaba.dashscope.audio.ttsv2.enrollment.Voice;
import com.alibaba.dashscope.audio.ttsv2.enrollment.VoiceEnrollmentService;
import com.alibaba.dashscope.exception.InputRequiredException;
import com.alibaba.dashscope.exception.NoApiKeyException;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import static java.lang.System.exit;

public class VoiceEnrollmentSampleCodes {
    public static String apiKey = "sk-7dd82cacca8f4f258a2e2be66a88beb4";  // 如果您没有配置环境变量，请在此处用您的API-KEY进行替换
    private static String fileUrl = "https://lean-ai.oss-cn-hangzhou.aliyuncs.com/%E5%86%AC%E5%A4%A9.wav?OSSAccessKeyId=LTAI5tAoSVxBhEHjtf6AYs9v&Expires=1755622803&Signature=WKJY7IvVugydGEuE0v02GppwoXw%3D";  // 请按实际情况进行替换
    private static String prefix = "prefix";
    private static String targetModel = "cosyvoice-v2";

    public static void main(String[] args)
            throws NoApiKeyException, InputRequiredException {
        // 复刻声音
        VoiceEnrollmentService service = new VoiceEnrollmentService(apiKey);
        Voice myVoice = service.createVoice(targetModel, prefix, fileUrl);
        System.out.println("RequestId: " + service.getLastRequestId());
        System.out.println("your voice id is " + myVoice.getVoiceId());


        // 使用复刻的声音来合成文本为语音
        SpeechSynthesisParam param = SpeechSynthesisParam.builder()
                .apiKey(apiKey)
                .model(targetModel)
                .voice(myVoice.getVoiceId())
                .build();
        SpeechSynthesizer synthesizer = new SpeechSynthesizer(param, null);
        ByteBuffer audio = synthesizer.call("白水, 你好吗, 好久不见, 最近在研究什么, 要不要和我处cp？");
        // 保存合成的语音到文件
        System.out.println("TTS RequestId: " + synthesizer.getLastRequestId());
        File file = new File("D:\\test\\demo\\demo.mp3");
        try (FileOutputStream fos = new FileOutputStream(file)) {
            fos.write(audio.array());
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        exit(0);
    }
}
